package com.ff.discounts.component.search
import android.view.Menu
import android.view.View
import androidx.appcompat.widget.SearchView
import com.ff.discounts.superui.extension.show
import com.ff.discounts.R
import com.ff.discounts.activity.BaseTitleActivity
import com.ff.discounts.databinding.ActivitySearchBinding
import com.ff.discounts.databinding.HeaderSearchBinding
import com.ff.discounts.databinding.ItemSearchHistoryBinding
import com.ff.discounts.databinding.ItemSearchPopularityBinding
import com.ff.discounts.superui.util.SuperKeyboardUtil
import com.ff.discounts.superui.util.SuperTabUtil
import com.ff.discounts.util.SuperRecyclerViewUtil
import org.apache.commons.lang3.StringUtils
import java.util.ArrayList

class SearchActivity : BaseTitleActivity<ActivitySearchBinding>() {
    private var suggestionRunnable: Runnable? = null
    private var data: String? = null
    private lateinit var searchView: SearchView

    private lateinit var searchHeaderAdapter: SearchHeaderAdapter
    private lateinit var headerSearchBinding: HeaderSearchBinding

    // 搜索结果适配器
    private lateinit var searchCategoryAdapter:SearchCategoryAdapter

    override fun initViews() {
        super.initViews()
        // RecycleView 的布局管理器
        SuperRecyclerViewUtil.initVerticalLinearRecyclerView(binding.list)

        // 内容滚动布局
        SuperTabUtil.bind(binding.indicator,binding.pager)
    }

    override fun initDatum() {
        super.initDatum()
        //头部
        headerSearchBinding = HeaderSearchBinding.inflate(layoutInflater,binding.list,false)
        searchHeaderAdapter = SearchHeaderAdapter(headerSearchBinding)
        searchCategoryAdapter = SearchCategoryAdapter(hostActivity)



        binding.list.adapter = searchHeaderAdapter

        //region  搜索结果适配器
        binding.pager.adapter = searchCategoryAdapter

        // 创建tab
        binding.indicator.removeAllTabs()
        for (title in indicatorTitles){
            binding.indicator.addTab(binding.indicator.newTab().setText(title))
        }
        searchCategoryAdapter.setDatum(indicatorTitles)
        binding.pager.offscreenPageLimit = indicatorTitles.size
        //endregion


        binding.pager.post{
            // 加载热门搜索
            loadHotData()
            loadSearchHistoryData()
        }

    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
       menuInflater.inflate(R.menu.search,menu)
        // 查找搜索按钮
        val searchItem = menu.findItem(R.id.action_search)
        // 查找控件
        searchView = searchItem.actionView as SearchView
        searchView.setOnQueryTextListener(object :SearchView.OnQueryTextListener{
            /**
             * 提交了搜索
             * 回车搜索调用两次
             * 点击键盘搜索
             *
             */
            override fun onQueryTextSubmit(query: String): Boolean {
                data = query
                performSearch()
                return  true
            }
            /**
             *  搜索框文本变了
             */
            override fun onQueryTextChange(newText: String?): Boolean {
                return true
            }
        })

        // 是否进入界面就打开搜索栏
        //false 为默认打开
        searchView.isIconified = false

        //设置关闭监听器
        searchView.setOnClickListener{
            // 显示搜索历史控件
            showSearchHistoryView()
            false
        }
        return true

    }
    /**
    *  执行搜索
    */
    private fun performSearch() {
        if(StringUtils.isEmpty(data)){
            // 没有数据直接返回
            return
        }
        // 保存搜索历史
        val searchHistory = SearchHistory()
        searchHistory.content = data
        searchHistory.createdAt = System.currentTimeMillis()
        getOrm().createOrUpdate(searchHistory)
        loadSearchHistoryData()

        // 显示搜索控件
        showSearchResultView()

    }



    /**
    * 显示搜索历史控件
    */
    private fun showSearchHistoryView(){
        binding.searchResultContainer.visibility = View.GONE
        binding.list.visibility = View.VISIBLE
    }

    /**
    * 显示搜索结果的控件
    */
    private fun showSearchResultView(){
        binding.searchResultContainer.visibility = View.VISIBLE
        binding.list.visibility = View.GONE

    }

    private fun loadHotData() {
        val datum:MutableList<String> = ArrayList()
        datum.add("护手霜")
        datum.add("女装")
        datum.add("java")

        // 设置热门搜索数据
        setPopularData(datum)
    }

    private fun setPopularData(datum: MutableList<String>) {
            for(data in datum){
                // 创建布局
                val itemSearchPopularityBinding = ItemSearchPopularityBinding.inflate(layoutInflater,binding.list,false)
                // 设置数据
                itemSearchPopularityBinding.title.text = data

                // 设置点击事件
                itemSearchPopularityBinding.root.setOnClickListener {
                     setSearchData(data)
                }
                // 添加控件
                headerSearchBinding.floatLayout.addView(itemSearchPopularityBinding.root)
            }
    }

    private fun setSearchData(data: String) {
        // 将内容设置到搜索控件
        // 并马上执行搜索
        searchView.setQuery(data,true)

        // 进入搜索状态
        searchView.isIconified = false

        // 隐藏软键盘
        SuperKeyboardUtil.hideKeyboard(hostActivity)
    }


    // 设置搜索历史
    private fun loadSearchHistoryData() {
        setHistoryData(getOrm().querySearchHistory() as MutableList<SearchHistory>)
        refreshSearchHistoryTitleStatus()
    }


    //设置搜索历史数据
    private fun setHistoryData(datum: MutableList<SearchHistory>) {
        headerSearchBinding.floatHistory.removeAllViews()
        for(data in datum){
            // 创建布局
            val itemSearchHistoryBinding = ItemSearchHistoryBinding.inflate(layoutInflater,binding.list,false)
            // 设置数据
            itemSearchHistoryBinding.title.text = data.content

            // 设置点击事件
            itemSearchHistoryBinding.root.setOnClickListener {
                setSearchData(data.content!!)
            }
            // 添加控件
            headerSearchBinding.floatHistory.addView(itemSearchHistoryBinding.root)
        }
    }

    // 显示搜索历史头部
    private fun refreshSearchHistoryTitleStatus() {
        headerSearchBinding.history.headerTitle.text = "搜索历史"
        headerSearchBinding.history.root.show(getOrm().querySearchHistory().isNotEmpty())
    }

    companion object{
        /**
        * 标题数据
        */
        private val indicatorTitles = listOf(
            R.string.tb,
            R.string.jd,
            R.string.pdd
        )

    }

}